//go:build darwin || windows
// +build darwin windows

package grpc

import (
	"context"
	"net"

	"github.com/shimingyah/pool"
	"google.golang.org/grpc"
)

var (
	RealAddr   string
	targetAddr = "localhost:80"
)

type GrpcConnOptions struct {
	Addr    string
	Network string
}

type GrpcConnPool struct {
	value pool.Pool
}

func NewGrpcConnPool(o *GrpcConnOptions) (g *GrpcConnPool, err error) {
	option := pool.DefaultOptions
	option.Dial = Dial
	option.MaxIdle = 30
	option.MaxActive = 200
	option.MaxConcurrentStreams = 200
	instance, err := pool.New("localhost:80", option)
	g = &GrpcConnPool{
		value: instance,
	}

	return
}

func Dial(address string) (*grpc.ClientConn, error) {
	ctx, cancel := context.WithTimeout(context.Background(), pool.DialTimeout)
	defer cancel()
	return grpc.DialContext(
		ctx,
		targetAddr,
		grpc.WithInsecure(),
		grpc.WithContextDialer(ContextDialer))
}

func ContextDialer(ctx context.Context, addr string) (net.Conn, error) {
	return DialContext(ctx, RealAddr)
}

func (g *GrpcConnPool) GetConn() (cc *grpc.ClientConn, err error) {
	conn, err := g.value.Get()
	if err != nil {
		return
	}
	defer conn.Close()

	cc = conn.Value()
	return
}

func (g *GrpcConnPool) Close() {
	g.value.Close()
}
